package util;

import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JTextArea;

public class Logger {

	public static final int FINEST = 0, FINER = 1, FINE = 2, NORMAL = 3,
			WARNING = 4, SEVERE = 5;
	private static int FILTER = FINER;
	private static boolean showSource = false;

	public static void setShowSource(boolean b) {
		showSource = true;
	}

	public static void log(Throwable t) {
		log(t, null);
	}

	public static void log(Throwable t, String msg) {
		if (FILTER > SEVERE)
			return;
		if (msg != null)
			System.err.println(msg);
		System.err.println(t);
		StackTraceElement[] trace = t.getStackTrace();
		for (StackTraceElement e : trace) {
			System.err.println(e.toString());
		}
	}

	public static void log(int SEVERITY, String message) {
		if (SEVERITY >= FILTER) {
			System.out.println(message);
		}
	}

	/**
	 * All messages at or above the given level will be logged.
	 */
	public static void setLogFilter(int SEVERITY) {
		FILTER = SEVERITY;
	}

	public static void lockOutputTo(JTextArea jta) {
		PrintStream rerouted = createOut(jta);
		System.setOut(rerouted);
		System.setErr(rerouted);
	}

	private static PrintStream createOut(final JTextArea jta) {
		PrintStream stream = new PrintStream(new OutputStream() {
			@Override
			public void write(int arg0) {
			}
		}) {
			@Override
			public void println(Object o) {
				println(o.toString());
			}

			@Override
			public void println(String s) {
				if (showSource) {
					StackTraceElement[] trace = new Exception().getStackTrace();
					for (int i = 1; i < trace.length; i++) {
						String className = trace[i].getClassName();
						if (className.contains("Logger") == false) {
							jta.append(className + " : "
									+ trace[i].getLineNumber() + " : ");
							break;
						}
					}
				}
				boolean scroll = jta.getCaretPosition() == jta.getDocument()
						.getLength();
				jta.append(s + '\n');
				if (scroll)
					jta.setCaretPosition(jta.getDocument().getLength());
				jta.repaint();
			}
		};
		return stream;
	}

}
